package com.shark.teach;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

/**
 * @auther shark
 * @create 2024-08-07 11:39
 */
public class MyThreadPoolDemo
{
    public static void main(String[] args)
    {

        System.out.println(Runtime.getRuntime().availableProcessors());

        ExecutorService threadPool = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors(),
                Runtime.getRuntime().availableProcessors() * 2,
                2L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        try
        {
            //类似顾客，20个请求线程
            for (int i = 1; i <= 8; i++) {
                int finalI = i;
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t"+"受理第："+ finalI +"个顾客");
                    try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }

    private static void init()
    {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池固定数线程，5个银行工作人员workThread
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1线程
        //ExecutorService threadPool = Executors.newCachedThreadPool();//一池N线程

        try
        {
            //类似顾客，20个请求线程
            for (int i = 1; i <= 20; i++) {
                int finalI = i;
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t"+"受理第："+ finalI +"个顾客");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}
